package com.qlhx.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.qlhx.common.model.ApiResult;
import com.qlhx.model.LoginModel;
import com.qlhx.model.User;
import com.qlhx.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value = "用户接口", description = "用户接口")
@CrossOrigin(maxAge = 3600)
@RestController
@Scope(value = "prototype") 
@RequestMapping("user")
public class UserController {
	
	private  final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	UserService userService;
	
	@Autowired
	RedisTemplate<String, Object> myRedis;
	
	@ApiOperation(value ="用户登录" ,notes ="用户登录")
	@RequestMapping(value = "/login",method = RequestMethod.POST, produces = {
    "application/json"}, consumes = {"application/json"})
	public @ResponseBody ApiResult<User> login(@RequestBody LoginModel loginModel, HttpServletRequest request
			)
	{
		ApiResult<User> result = new ApiResult<User>();
		try {
			String username = loginModel.getUsername();
			String password = loginModel.getPassword();
			logger.info("username=" + username + "  password=" + password);
			User user = userService.selectByUserNameAndPassword(username, password);
			if(user != null)
			{
				String token = this.saveToken(username);
				user.setToken(token);
				result.setContent(user);
			}
			else
			{
				result.setCode(ApiResult.PARAM_ERROR);
				result.setMsg("账号或密码错误");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("用户登录发生错误", e);
			result.getErrorResult(e);
		}

		return result;

	}
	
	@ApiOperation(value ="用户是否已登录" ,notes ="用户是否已登录")
	@RequestMapping(value = "/islogin/{token}",method = RequestMethod.GET, produces = {
    "application/json"})
	public @ResponseBody ApiResult<String> islogin(@PathVariable String token)
	{
		ApiResult<String> result = new ApiResult<String>();
		String username = (String)myRedis.opsForValue().get(token);
		logger.info("username=" + token);
		logger.info("username=" + username);
		
		if(StringUtils.isBlank(username))
		{
			logger.info("token=" + token+"  不存在，验证失败");
			result.setCode(ApiResult.NO_LOGIN);
			result.setMsg("未登录");
		}
		else
		{
			logger.info("token=" + token+" 验证成功,用户为:"+username);
			result.setContent(username);
		}
		return result;
	}
	

	
	private String saveToken(String username) throws Exception {
		String token = UUID.randomUUID().toString().replace("-", "");
		myRedis.opsForValue().set(token, username, 60000);
		logger.info("用户:"+username+" 登录成功,生成token:"+token);
		logger.info("========"+(String)myRedis.opsForValue().get(token));
		return token;
	}
}
